package com.leejie.controller;

import com.leejie.config.MyBeanPostProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author leejie
 * @date 2021/10/25 16:12
 */
@RestController
public class FileUploadController {

    Logger log = LoggerFactory.getLogger(FileUploadController.class);
    @Autowired
    MyBeanPostProcessor myBeanPostProcessor;

    @GetMapping("/file")
    public ModelAndView file(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("请求到这里了吗？---"+request.getRequestURI());
        System.out.println("---------------------------->>>>>>>"+myBeanPostProcessor);
        return new ModelAndView("index");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public HashMap<String, Object> fileUpload( MultipartFile file, HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();

            if (file.isEmpty()){
                System.out.println("文件为空...");
            }
            log.info("上传的文件： --->  "+file);
            String originalFilename = file.getOriginalFilename();
            log.info("文件名：----> "+originalFilename);
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("文件类型：----> "+fileType);
//        String filePath = "F://data//";
//        log.info("随机定义的文件名：----> "+originalFilename);
            String format = sdf.format(new Date());
            //上传到的路径
//            String realPath = "/data/files/"+format;
            String realPath = "D://data//"+format;
            File folder = new File(realPath);
            log.info("文件的上传路径：----> "+folder);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String newName = UUID.randomUUID() + fileType;
            try {
                file.transferTo(new File(folder,newName));
                String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+format+newName;
                System.out.println("====================="+url);
                result.put("status","success!!!");
                result.put("url",url);
                log.info("文件上传成功 ---> success");
            } catch (IOException e) {
                e.printStackTrace();
                result.put("status","error!!!");
                result.put("msg",e.getMessage());
                log.info("文件上传失败 ---> "+e.getMessage());
            }
        return result;
    }


    @GetMapping("/download")
    public ResponseEntity download() throws IOException {
        FileSystemResource file = new FileSystemResource("D:\\data\\2021\\11\\15\\fb76855f-e5c7-47b9-82c5-8ad3b94f663e.md");
        HttpHeaders headers = new HttpHeaders();
        String fileName = file.getFilename();
        log.info("下载的文件名："+fileName);
        headers.add("Content-Disposition","attachment;filename="+fileName);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(file);
    }

}
